package cn.zjutleo.village_server.service;

import cn.zjutleo.village_server.config.SmsConfig;
import cn.zjutleo.village_server.constants.RedisConstants;
import cn.zjutleo.village_server.exception.apiException.smsException.MessageCheckException;
import cn.zjutleo.village_server.exception.apiException.smsException.MessageSendException;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Random;

/**
 * @author : Qin Zhenghan
 * @date : Created in 2021/8/23
 * @description: 腾讯云SMS短信业务类
 */
@Slf4j
@Component
public class SmsService {
    @Resource
    private RedisService redisService;
    @Resource
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public boolean sendMessage(String phone, String type) {
        try {
            // 随机生成6位验证码
            String code = makeSmsCode(6);
            switch (type) {
                case "login": {
                    redisService.set(RedisConstants.LOGIN_BY_PHONE_CODE_PREFIX + phone, code, smsConfig.getExpireTime() * 60);
                    break;
                }
                default: {
                    throw new MessageSendException("type字段值错误! ");
                }
            }
            // 短信模板参数（验证码 & 过期时间）
            String[] params = {code, String.valueOf(smsConfig.getExpireTime())};
            SmsSingleSender smsSingleSender = new SmsSingleSender(smsConfig.getAppId(), smsConfig.getAppKey());
            SmsSingleSenderResult result = smsSingleSender.sendWithParam(smsConfig.getRegion(), phone, smsConfig.getTemplateId(), params, smsConfig.getSignName(), "", "");
        } catch (HTTPException | JSONException | IOException | MessageSendException e) {
            System.out.println(e.getMessage());
        }
        return true;
    }

    /**
     * 生成随机验证码
     *
     * @param length 随机验证码的长度
     * @return 随机验证码
     */
    public String makeSmsCode(int length) {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int next = random.nextInt(10);
            code.append(next);
        }
        return code.toString();
    }

    /**
     * 校验手机验证码
     *
     * @param phone 手机号
     * @param code 输入验证码
     * @return 校验结果
     */
    public boolean verifyCode(String phone, String code) throws MessageCheckException {
        String realCode = (String) redisService.get(RedisConstants.LOGIN_BY_PHONE_CODE_PREFIX + phone);
        if (realCode == null) {
            throw new MessageCheckException("验证码验证失败！");
        }
        return realCode.equals(code);
    }
}
